rm(list= ls())

outcomes <- c('cdu_csu', 'spd', 'far_right_vs_excl_dp', 'fdp')

## Load Election Data

dat <- readRDS('data/fed_elections_kreise.rds') %>%
  filter(year >= 1953) %>% 
  filter(year <= 1965) %>%
  filter(type == 'Stadtkreis') %>%
  dplyr::select(one_of('county_id_1950', 'year', outcomes)) 

## Store synagogues 

treatment <- readRDS('data/fed_elections_kreise.rds') %>%
  dplyr::select(one_of('county_id_1950', 'n_syn_bin')) %>% 
  distinct(county_id_1950, .keep_all = T)

## Pivot longer for summarizing and plotting 

dat_long <- dat %>%
  pivot_longer(cols = 3:ncol(.),
               names_to = 'party', 
               values_to = 'voteshare') %>%
  left_join(treatment) %>%
  mutate(party = recode(party,
                        `drp` = 'DRP',
                        `dp` = 'DP',
                        `far_right_vs` = 'Far right\n(NPD + DRP + DP)',
                        `far_right_vs_excl_dp` = 'Far right\n(NPD + DRP)',
                        `npd` = 'NPD', 
                        `other` = 'Small parties\n(not SPD/CDU/FDP)',
                        `turnout` = 'Turnout',
                        `spd` = 'SPD',
                        `cdu_csu` = 'CDU/CSU',
                        `fdp` = 'FDP')) %>%
  mutate_at('n_syn_bin', as.factor)

## Summarize data  

plot_df <- dat_long %>% 
    group_by(.dots = c('n_syn_bin', 'party', 'year')) %>%
    summarise(vs_mean = mean(voteshare, na.rm = T),
              vs_mean_se = haschaR::se_mean(voteshare)) %>%
    ungroup() %>% 
    mutate(vs_low = vs_mean - 1.96*vs_mean_se,
           vs_high = vs_mean + 1.96*vs_mean_se) %>%
    filter(!is.na(n_syn_bin)) %>% ## remove NAs 
    rename('treated' = 1) 

## Plot This 

pd <- position_dodge(.3)

ggplot(plot_df, aes(x = year, y = vs_mean, ymin = vs_low, ymax = vs_high, 
                     group = treated, 
                     col = treated,
                     shape = treated)) + 
  geom_point(position = pd) + 
  geom_errorbar(width = 0, position = pd) + 
  theme_classic() + 
  geom_line() + 
  facet_grid(rows = vars(party), 
             scales = 'free') + 
  scale_x_continuous(breaks = unique(plot_df$year)) + 
  geom_vline(xintercept = 1963.5, linetype = 'solid') + 
  scale_shape_discrete(labels = c('No synagogue in city', 'Synagogue in city')) + 
  scale_color_manual(labels = c('No synagogue in city', 'Synagogue in city'),
                     values = c('grey', 'black')) + 
  theme(legend.position = 'bottom',
        legend.title = element_blank()) + 
  labs(x = 'Election period',
       y = 'Mean vote share in % points')  


